<script>
  import { onMount } from 'svelte';
  let name = 'world';
  let data = [];

  const { invoke } = window._.tauri;
  const { Command } = window._.shell;

  const onMessage = (e) => {
    console.log('iframe recv: ', e);
    data.push(e.data);
  };
  onMount(() => {
    invoke('getenv', { name: 'PATH' }).then((res) => {
      console.log('plugin:port-forward:', res);
    });
  });

  const add = (srcPort, dstIP, dstPort) => {
    const cmd = `chcp 65001 & netsh interface portproxy add v4tov4 listenport=${srcPort} connectaddress=${dstIP} connectport=${dstPort}`;
    const { port1, port2 } = new MessageChannel();
    port1.onmessage = onMessage;
    window.parent.postMessage(
      JSON.stringify({
        __func__: 'shell.Command',
        args: {
          program: 'cmd',
          args: ['/C', cmd],
        },
      }),
      '*',
      [port2],
    );
  };
  onMount(() => {
    new Command('cmd', [
      '/C',
      'chcp 65001 & netsh interface portproxy show all',
    ])
      .execute()
      .then((output) => {
        console.log(output);
      });
  });
  onMount(() => {
    const command = new Command('cmd', [
      '/C',
      'chcp 65001 & netsh interface portproxy show all',
    ]);

    command.on('close', (data) => {
      console.log(
        `command finished with code ${data.code} and signal ${data.signal}`,
      );
    });
    command.on('error', (error) => console.error(`command error: "${error}"`));
    command.stdout.on('data', (line) =>
      console.log(`command stdout: "${line}"`),
    );
    command.stderr.on('data', (line) =>
      console.log(`command stderr: "${line}"`),
    );

    command.spawn().then((child) => {
      console.log('pid:', child.pid);
    });
  });
</script>

<h1>Hello {name}!</h1>
<button on:click={() => add(1234, '9.172.7.2', 5432)}>新增</button>
